<template>
  <div class="create-post-page">
    <h4>新建文章</h4>
    <Uploader
      action="/api/upload"
      :beforeUpload="uploadCheck"
      @file-uploaded="handleFileUpload"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
    >
      <h2>点击上传头图</h2>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" role="status">
            <span class="visually-hidden">Loading...</span>
          </div>
          <h2 class="ms-3">正在上传</h2>
        </div>
      </template>
      <template #uploaded="dataProps">
        <img :src="dataProps.uploadedData.url" />
      </template>
    </Uploader>
    <ValidateForm @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-babel">文章标题：</label>
        <ValidateInput
          :rules="titleRules"
          v-model="titleVal"
          placeholder="请输入文章标题"
          type="text"
          tag="input"
        >
        </ValidateInput>
      </div>
      <div class="mb-3">
        <label class="form-label">文章详情</label>
        <ValidateInput
          :rules="contentRules"
          v-model="contentVal"
          placeholder="请输入文章详情"
          type="text"
          tag="textarea"
        >
        </ValidateInput>
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">发表文章</button>
      </template>
    </ValidateForm>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import ValidateForm from "@/components/ValidateForm.vue";
import ValidateInput, { RulesProp } from "@/components/ValidateInput.vue";
import { GlobalDataProps, PostProps, ResponseType, ImageProps } from "@/store";
import createMessage from "@/components/createMessage";
import Uploader from "@/components/Uploader.vue";
import { beforeUploadCheck } from "@/util/helper";

const router = useRouter();
const store = useStore<GlobalDataProps>();

const titleVal = ref("");
const titleRules: RulesProp = [
  {
    type: "required",
    message: "文章标题不能为空",
  },
];

const contentVal = ref("");
const contentRules: RulesProp = [
  {
    type: "required",
    message: "文章详情不能为空",
  },
];

//表单提交事件
const onFormSubmit = (result: boolean) => {
  if (result) {
    // 获取专栏id和用户id
    const { column = "", _id } = store.state.user;
    const newPost: PostProps = {
      // _id: new Date().toLocaleTimeString(),
      title: titleVal.value,
      content: contentVal.value,
      column,
      // createdAt: new Date().toLocaleString(),
      author: _id,
    };
    // 有上传图片时，把图片id一起发送
    if (imageId) {
      newPost.image = imageId;
    }

    store.dispatch("createPost", newPost).then((res) => {
      router.push({
        path: "/column/" + res.column,
      });
    });
  }
};

// 旧的校验
/* const beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg'
    if (!isJPG) {
        createMessage('上传图片只能是 JPG 格式', 'error')
    }
    return isJPG
}

// 响应对象的类型ResponseType， 里面的data类型为图片的类型ImageProps
const onFileUploaded = (rawData: ResponseType<ImageProps>) => {
    if (rawData.code === 0) {
        createMessage('上传成功', 'success')
    }
}

const onFileUploadedError = (err: Error) => {
    createMessage('上传失败', 'error')
} */

// 上传检验
const uploadCheck = (file: File) => {
  const condition = {
    format: ["image/jpeg", "image/png"],
    size: 1,
  };
  const result = beforeUploadCheck(file, condition);
  const { passed, error } = result;
  if (error === "format") {
    createMessage("上传图片只能是 JPG/PNG 格式", "error");
  }
  if (error === "size") {
    createMessage("上传图片大小不能超过 1Mb", "error");
  }
  return passed;
};

// 头图上传后的id
let imageId = "";
// 监听上传成功后的操作
const handleFileUpload = (rwaData: ResponseType<ImageProps>) => {
  if (rwaData.data._id) {
    imageId = rwaData.data._id;
  }
};
</script>

<style lang="scss">
/* 不要加scoped */
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
}

.create-post-page .file-upload-container img {
  object-fit: contain;
  width: 100%;
  height: 100%;
}
</style>
